package sys_post_dao

import (
	"database/sql"
	"gf-admin/app/pojo/sys/sys_post"
	"gf-admin/library/service"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
)

func List(req *sys_post.SearchParams) (total, page int, list gdb.Result, err error) {
	model := g.DB().Table(sys_post.Table)

	if req != nil {
		if req.PostCode != "" {
			model.Where("post_code like ?", "%"+req.PostCode+"%")
		}

		if req.PostName != "" {
			model.Where("post_name like ?", "%"+req.PostName+"%")
		}

		if req.Status != "" {
			model.Where("status", req.Status)
		}
	}

	total, err = model.Count()

	if err != nil {
		g.Log().Error(err)
		err = gerror.New("获取总行数失败")
	}

	if req.PageNum == 0 {
		req.PageNum = 1
	}

	page = req.PageNum

	if req.PageSize == 0 {
		req.PageSize = service.AdminPageNum
	}

	list, err = model.Page(page, req.PageSize).All()

	//g.Log().Println(list)
	if err != nil {
		g.Log().Error(err)
		err = gerror.New("获取数据失败")
		return
	}

	return
}

//获取正常状态的岗位
func GetUsedPost() (list []*sys_post.Entity, err error) {
	list, err = sys_post.Model.Where(sys_post.Columns.Status, 1).Order(sys_post.Columns.PostSort + " ASC, " + sys_post.Columns.PostId + " ASC ").All()
	if err != nil {
		g.Log().Error(err)
		err = gerror.New("获取岗位数据失败")
	}
	return
}

/**
添加
*/
func Add(addParams *sys_post.AddParams) (result sql.Result, err error) {
	entity := &sys_post.Entity{
		PostCode:   addParams.PostCode,
		PostName:   addParams.PostName,
		PostSort:   addParams.PostSort,
		Status:     addParams.Status,
		Remark:     addParams.Remark,
		CreateBy:   gconv.String(addParams.AddUser),
		CreateTime: gtime.Now(),
	}

	return sys_post.Model.Save(entity)

}

func Edit(editParams *sys_post.EditParams) (result sql.Result, err error) {
	var entity *sys_post.Entity
	entity, err = sys_post.Model.FindOne(editParams.PostId)
	entity.PostId = editParams.PostId
	entity.PostCode = editParams.PostCode
	entity.PostName = editParams.PostName
	entity.PostSort = editParams.PostSort
	entity.Status = editParams.Status
	entity.Remark = editParams.Remark
	entity.UpdateBy = gconv.String(editParams.UpUser)
	entity.UpdateTime = gtime.Now()
	if entity.CreateTime == nil {
		entity.CreateTime = entity.UpdateTime
	}
	return sys_post.Model.Save(entity)
}

func GetOneById(id int64) (*sys_post.Entity, error) {
	return sys_post.Model.One(g.Map{
		"post_id": id,
	})
}

func DeleteByIds(ids []int) error {
	_, err := sys_post.Model.Delete("post_id IN(?)", ids)
	if err != nil {
		g.Log().Error(err)
		return gerror.New("删除失败")
	}
	return nil
}
